layui.use(['form', 'http', 'public'], function () {
    onLoad();
    layui.form.on('submit(userLogin)', function () {
        layui.layer.load();
        let postData = {
            type: 'user',
            username: $('input[name="u_name"]').val() || '',
            userpass: $('input[name="u_pass"]').val() || '',
        };
        Login(postData);
        return false;
    })

    layui.form.on('submit(phoneLogin)', function () {
        layui.layer.load();
        let postData = {
            type: 'phone',
            number: $('input[name="u_phone"]').val() || '',
            code: $('input[name="u_code"]').val() || ''
        };
        Login(postData);
        return false;
    })
});

function onLoad() {
    let data = {};
    if (user_token) {
        layui.http.SendAjax(shopUrl + '/api/member/info/', {async: 1}, {token: user_token}, function (res) {
            data = res.data || {};
        })
    }
    layui.public.ViewTpl(data, 'view_body_data', 'view_body');
}

function phoneCode() {
    let number = $('input[name="u_phone"]').val() || '';
    if (number == '') {
        layui.layer.msg('手机号码必须填写');
        $('input[name=u_phone]').focus();
        return false;
    }
    let postData = {
        type: 'phone',
        number: $('input[name="u_phone"]').val() || '',
    };
    layui.layer.load();
    layui.http.SendAjax(shopUrl + '/api/member/getcode/', postData, [], function (res) {
        layui.layer.closeAll('loading');
        layui.layer.msg(res.msg);
        if (res.code == 200) {
            $(".phonebutton").removeClass('layui-btn-normal');
            $(".phonebutton").addClass('layui-btn-disabled');
            $(".phonebutton").removeAttr("onclick");
            $(".phonebutton").html("已发送");
        }
        return false;
    })
}

function Login(postData = []) {
    layui.http.SendAjax(shopUrl + '/api/member/login/', postData, [], function (res) {
        layui.layer.closeAll('loading');
        layui.layer.msg(res.msg);
        saveToken(res);
    })
}

function saveToken(res = []) {
    if (res.code == 200) {
        localStorage.setItem("user_token", res.data.user_token);
        user_token = res.data.user_token;
        onLoad();
    }
}

function loginOut() {
    layer.confirm('确定要退出登录吗？', function (index) {
        layer.close(index);
        localStorage.setItem("user_token", '');
        user_token = '';
        onLoad();
    })
}

function inUser() {

}